import React, { useState, useEffect } from 'react';
import styles from './RightPannel.less';
import classNames from 'classnames';
import { connect } from 'umi';
import { EventItemType, ButtonType } from '../dict';
import { Form, Tabs, Input, Table, Switch, Select } from 'antd';
import * as api from '../service';
import { useCanvasContext } from '../CanvasContext';
import NodeMember from './NodeMember';
import { cloneDeep } from '@antv/x6/lib/util/object/object';

const img = require('@/assets/styles/container.png');
const imgForm = require('@/assets/styles/basicFrom.png');
const imgMember = require('@/assets/styles/member.png');
const imgPermission = require('@/assets/styles/permission.png');
const imgOperate = require('@/assets/styles/imgOperate.png');
const orgImg = require('@/assets/styles/orgImg.png');
const roleImg = require('@/assets/styles/roleImg.png');
const accImg = require('@/assets/styles/accImg.png');

function WorkView(props) {
  const { wfeditor, dispatch, appId } = props;
  const { selectedId, selectedObj, formList } = wfeditor;
  const canvasContext = useCanvasContext();

  const [currentRecord, setCurrentRecord] = useState({});
  const [isModalVisible, setIsModalVisble] = useState(false);
  const [isSendVisible, setIsSendVisble] = useState(false);
  const [basicFormFields, setBasicFormFields] = useState([
    { name: ['desc'], value: '' },
    { name: ['nodeDesc'], value: '' },
  ]);
  const [currentMember, setCurrentMember] = useState([]);
  const [currentSend, setCurrentSend] = useState([]);
  const [currentForm, setCurrentForm] = useState({
    projectId: '',
    pageId: '',
    pageNameCh: '',
    pageNameEn: '',
    pagePath: '',
    pageType: '',
  });
  const [selectFormList, setSelectFormList] = useState([]);
  const [operateData, setOperateData] = useState([]);
  const operateColumns = [
    {
      title: '按钮',
      dataIndex: 'value',
      with: 80,
      key: 'value',
      render: (text, record) => {
        return <div>{ButtonType[record.value]}</div>;
      },
    },
    {
      title: '显示名称',
      with: 160,
      dataIndex: 'label',
      key: 'label',
      render: (text, record) => (
        <>
          {currentRecord.value && currentRecord.value == record.value ? (
            <Input
              onBlur={(e) => {
                setCurrentRecord({});
              }}
              onChange={(e) => changeShowName(e, record)}
              defaultValue={record.label}
            ></Input>
          ) : (
            <span
              onClick={(e) => {
                setCurrentRecord(record);
              }}
            >
              {record.label}
            </span>
          )}
        </>
      ),
    },
    {
      title: '启用',
      with: 40,
      key: 'status',
      dataIndex: 'status',
      render: (text, record) => (
        <>
          <Switch checked={record.status} onClick={(e) => changeShowStatus(e, record)} />
        </>
      ),
    },
  ];

  const changeShowName = (e, record) => {
    record.label = e.target.value;
    let value = operateData;
    updateNode('operateData', value);
  };

  const changeShowStatus = (e, record) => {
    record.status = e;
    let value = operateData;
    updateNode('operateData', value);
  };

  const updateNode = (key, value) => {
    dispatch({
      type: 'wfeditor/updateCellEffect',
      payload: { id: selectedId, prop: key, value },
    });
    canvasContext.updateGraphProps(selectedId, 'data', {
      [key]: value,
    });
  };

  useEffect(() => {
    if (selectedId) intWorkView();
  }, [selectedId]);

  const intWorkView = () => {
    wfeditor.propList.length &&
      wfeditor.propList.forEach((item) => {
        if (item.id == selectedId) {
          console.log('intWorkView', item);
          setBasicFormFields([
            { name: ['desc'], value: item.data.desc },
            { name: ['nodeDesc'], value: item.data.nodeDesc },
          ]);
          setCurrentMember(item.data.memberList || []);
          setCurrentSend(item.data.sendList || []);
          setSelectFormList(formList);
          setCurrentForm(item.data.formKey);
          let params = {
            type: 'WorkTask',
          };
          if (item.data.operateData && item.data.operateData.length) {
            setOperateData(item.data.operateData);
          } else {
            api.getBtnList(params).then((r) => {
              if (r.code && r.code == '200') {
                if (!r.data[0].id) {
                  r.data.forEach((item) => {
                    item.label = item.name;
                    item.status = false;
                  });
                  setOperateData(r.data);
                }
              }
            });
          }
        }
      });
  };

  const changeFormSelect = (value) => {
    let arr = selectFormList;
    let fields = cloneDeep(basicFormFields);
    let currentItem;
    arr.forEach((item) => {
      if (item.pageNameEn == value) {
        currentItem = item;
      }
    });
    setCurrentForm(currentItem);
    updateNode('formKey', currentItem);
  };

  const onBasicValuesChange = (changedValues, allValues) => {
    const keys = Object.keys(changedValues);
    if (keys.length < 1) return;
    const key = keys[0];
    const value = changedValues[key];
    switch (key) {
      case 'desc':
        dispatch({
          type: 'wfeditor/updateCellEffect',
          payload: { id: selectedId, prop: key, value },
        });
        canvasContext.updateGraphProps(selectedId, 'data/desc', value);
        break;
      case 'nodeDesc':
        updateNode(key, value);
        break;
      default:
        updateNode(key, value);
        break;
    }
  };

  const setMemberView = () => {
    setIsModalVisble(true);
  };
  const setSendView = () => {
    setIsSendVisble(true);
  };
  const handleOk = (member, type) => {
    const value = member;
    setCurrentMember(value);
    updateNode('memberList', value);
    setIsModalVisble(false);
  };
  const handleCancel = () => {
    setIsModalVisble(false);
  };

  // 抄送人员
  const handleSendOk = (send, type) => {
    const value = send;
    setCurrentSend(value);
    updateNode('sendList', value);
    setIsSendVisble(false);
  };
  const handleSendCancel = () => {
    setIsSendVisble(false);
  };

  return (
    <div>
      <div className={classNames(styles.block, styles.basicInfo)}>
        <Form
          name="basic"
          fields={basicFormFields}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onValuesChange={onBasicValuesChange}
        >
          <div className={styles.secTitle}>
            <img src={img} />
            <span>基本信息</span>
          </div>
          <Form.Item
            label="节点名称"
            name="desc"
            rules={[{ required: false, message: '请输入节点名称' }]}
          >
            <Input placeholder="请输入节点名称" />
          </Form.Item>

          <Form.Item label="节点描述" name="nodeDesc">
            <Input.TextArea placeholder="请在此输入描述" />
          </Form.Item>
          <Tabs>
            <Tabs.TabPane tab={'基础属性'} key={'basicProps'}>
              <div className={styles.block}>
                <div className={styles.secTitle}>
                  <img src={imgForm} />
                  <span>节点表单</span>
                </div>

                <div className={styles.FormKeyItem}>
                  <div className={styles.formLabel}>表单名称：</div>
                  <Select
                    value={currentForm.pageNameEn}
                    onChange={changeFormSelect}
                    style={{ width: '203.25px' }}
                  >
                    {selectFormList.map((item) => {
                      return (
                        <Option key={item.id} value={item.pageNameEn}>
                          {item.pageNameCh}
                        </Option>
                      );
                    })}
                  </Select>
                </div>
                <div className={styles.FormKeyItem}>
                  <div className={styles.formLabel}>表单URL：</div>
                  <Input style={{ width: '203.25px' }} value={currentForm.pagePath} readOnly />
                </div>
                <div className={styles.secTitle}>
                  <img src={imgMember} />
                  <span>节点人员</span>
                </div>
                <div onClick={setMemberView} className={styles.addMember}>
                  {currentMember.length == 0 ? '+ 点击设置节点人员' : null}
                  {currentMember.length ? (
                    <div className={styles['member-list']}>
                      {currentMember.length &&
                        currentMember.map((node, i) => {
                          return (
                            <div className={styles['member-name-card']} key={node.key}>
                              {node.type == 'org' && <img src={orgImg} />}
                              {node.type == 'role' && <img src={roleImg} />}
                              {node.type == 'acct' && (
                                <div className={styles['member-name-acct']}>{node.title[0]}</div>
                              )}
                              {node.type == 'dynamic' && <img src={accImg} />}
                              <span>{node.title}</span>
                            </div>
                          );
                        })}
                    </div>
                  ) : null}
                </div>
                <div className={styles.secTitle}>
                  <img src={imgPermission} />
                  <span>抄送人员</span>
                </div>
                <div onClick={setSendView} className={styles.addMember}>
                  {currentSend.length == 0 ? '+ 点击设置抄送人员' : null}
                  {currentSend.length ? (
                    <div className={styles['member-list']}>
                      {currentSend.length &&
                        currentSend.map((node, i) => {
                          return (
                            <div className={styles['member-name-card']} key={node.key}>
                              {node.type == 'org' && <img src={orgImg} />}
                              {node.type == 'role' && <img src={roleImg} />}
                              {node.type == 'acct' && (
                                <div className={styles['member-name-acct']}>{node.title[0]}</div>
                              )}
                              {node.type == 'dynamic' && <img src={accImg} />}
                              <span>{node.title}</span>
                            </div>
                          );
                        })}
                    </div>
                  ) : null}
                </div>
              </div>
            </Tabs.TabPane>

            <Tabs.TabPane tab={'高级属性'} key={'advanceProps'}>
              <div className={styles.block}>
                <div className={styles.secTitle}>
                  <img src={imgOperate} />
                  <span>节点操作</span>
                </div>
                <Table
                  key="value"
                  columns={operateColumns}
                  dataSource={operateData}
                  pagination={false}
                />
              </div>
            </Tabs.TabPane>
          </Tabs>
        </Form>
        {isModalVisible && (
          <NodeMember
            title={'节点人员'}
            appId={appId}
            wfeditor={wfeditor}
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
          />
        )}
        {isSendVisible && (
          <NodeMember
            title={'抄送人员'}
            appId={appId}
            wfeditor={wfeditor}
            visible={isSendVisible}
            onOk={handleSendOk}
            onCancel={handleSendCancel}
          />
        )}
      </div>
    </div>
  );
}

export default connect(({ wfeditor }) => ({ wfeditor }))(WorkView);
